﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DMS.Base;
using DMS.Business.Modules.Organization;
using DMS.Business.Utility;
using DMS.Data;

namespace DMS.Business.Modules.LeaveWord
{
    public class LeaveWordService
    {
        public static void AddLeaveWord(string content)
        {
            using (var db = new DMSEntities())
            {
                if(!string.IsNullOrEmpty(content))
                {
                    var leaveWord = new SYS_LeaveWords();
                    leaveWord.LeaveWordID = Guid.NewGuid().ToString();
                    leaveWord.Content = content;
                    leaveWord.LeaveTime = DateTime.Now;
                    AuthenticationUser user = SystemContext.Current.LoginAuthUser;
                    leaveWord.LeaverID = user.ID;
                    leaveWord.Leaver = user.Name;

                    db.SYS_LeaveWords.AddObject(leaveWord);
                    db.SaveChanges();
                }
            }
        }

        public static int CountLeaveWord(string condition)
        {
            string countSql = String.Format(@"select count(*) num
	                                            from dbo.SYS_LeaveWords n 
                                            where 1=1                                           
                                            {0}", condition);
            DbCommand command = DBHelper.Instance.GetSqlStringCommand(countSql);
            DataSet ds = DBHelper.Instance.ExecuteDataSet(command);
            return Convert.ToInt32(ds.Tables[0].Rows[0]["num"]);
        }

        public static DataSet ListLeaveWord(int pageSize, int pageIndex, int total, string condition)
        {
            string sql = String.Format(@"select *
	                                        from SYS_LeaveWords n 
                                        where 1=1 
                                        {0} order by leaveTime desc", condition);
            SqlCommand command = new SqlCommand(sql, new SqlConnection(DBHelper.Instance.ConnectionString));
            SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
            DataSet ds = new DataSet();
            dataAdapter.Fill(ds, pageIndex - 1, pageSize, "Table1");
            return ds;
        }

        public static void DeleteLeaveWord(string leavewordId)
        {
            using(DMSEntities db = new DMSEntities())
            {
                var word = db.SYS_LeaveWords.Where(t => t.LeaveWordID == leavewordId).FirstOrDefault();
                db.SYS_LeaveWords.DeleteObject(word);
                db.SaveChanges();
            }
        }
    }
}
